#!/usr/bin/env python
#
# This script extracts all plans from its stdin, invokes dot on them
# to make a multi-page pdf / open to display them
#
import os
import fileinput

files = []

in_graphviz = False

# Note we  combine multiple digraphs
for line in fileinput.input():
    line = line.strip()

    if line.startswith("// Begin DataFusion GraphViz Plan"):
        filename = "/tmp/plan{}.ps".format(len(files))
        files.append(filename)
        f = open(filename, "w")
        in_graphviz = True

    if in_graphviz:
        f.write(line)
        f.write("\n")

    if line.startswith("// End DataFusion GraphViz Plan"):
        in_graphviz = False
        f = None

# try to ensure any open is closed
f = None


# TODO make this not mac specific
if len(files) > 0:
    #print("Found files: {}".format(files))
    print("Found {} graphs, converting to ps".format(len(files)))
    # convert them to ps files
    ps_files = []
    for file in files:
        output_file = "{}.pdf".format(file)
        os.system("dot -Tpdf < {}  > {}.pdf".format(file, output_file))
        ps_files.append(output_file)

    # combine all the postscript files together
    cmd =  "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=/tmp/plan.pdf {}".format(" ".join(ps_files))

    print("Running command:", cmd)
    os.system(cmd)

    print("Opening with system viewer")
    os.system('open /tmp/plan.pdf')
